package com.xhwl.data.initial;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhwl.common.dto.cent.sdata.PermissionGroupDTO;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.query.cent.sdata.PermissionQuery;
import com.xhwl.data.service.*;
import com.xhwl.data.service.devplatform.IDeveloperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: luyi
 * @Description: 运管平台帐号角色初始化， administrator没有角色的时候给administrator帐号富于全部权限的角色
 * @Date: Create in 16:34 2022/9/17
 */
@Component
@DependsOn("flywayInitializer")
public class OamInitial {


    @Autowired
    private IAdminAccountService adminAccountService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IAdminAccountRoleService adminAccountRoleService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAppService appService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    @Autowired
    private IDeveloperService developerService;

    private static final Logger log = LoggerFactory.getLogger(OamInitial.class);

    @Autowired
    private OpenPlatformInitial openPlatformInitial;

    @PostConstruct
    public void start(){
        log.info("开始初始化运管帐号默认角色");
        QueryWrapper<AdminAccount> adminAccountQueryWrapper = new QueryWrapper<>();
        adminAccountQueryWrapper.eq("login_name", "administrator");
        AdminAccount one = null;
        try {
            one = adminAccountService.getOne(adminAccountQueryWrapper);
        }catch (Exception e){
            log.error("查询运管帐号错误，初始化终止");
            e.printStackTrace();
        }
        if(null == one){
            log.info("administrator 帐号不存在初始化结束");
            return;
        }
        QueryWrapper<AdminAccountRole> adminAccountRoleQueryWrapper = new QueryWrapper<>();
        adminAccountRoleQueryWrapper.eq("admin_account_id", one.getId());
        List<AdminAccountRole> list = adminAccountRoleService.list(adminAccountRoleQueryWrapper);
        if(!list.isEmpty()){
            log.info("administrator 已经存在角色不需要初始化，结束");
            return;
        }

        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("app_id", "202012159464");
        App app = null;
        try {
            app = appService.getOne(appQueryWrapper);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(null == app){
            log.info("运管平台app不存在，初始化终止");
            return;
        }
        // 新增管理员角色和权限
        Role role = new Role();
        role.setIndustryId((short)0);
        role.setName("管理员");
        role.setCode("oamadmin");
        role.setGrade((short)2);
        role.setType(3);
        role.setIsInitialized(true);
        role.setLevel(1);
        role.setSortNum(1);
        role.setParentId(0);
        role.setStatus((short) 1);
        role.setIsDeleted(false);
        role.setAppId(app.getId());
        roleService.save(role);

        // 查询权限菜单
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("app_id", app.getId());
        List<Permission> list1 = permissionService.list(permissionQueryWrapper);
        if(list1.isEmpty()){
            log.info("运管菜单不存在，需要先导入菜单");
            return;
        }

        // 给管理员角色增加权限
        List<RolePermission> rolePermissions = new ArrayList<>(list1.size());
        for (Permission permission : list1) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permission.getId());
            rolePermissions.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissions);

        AdminAccountRole adminAccountRole = new AdminAccountRole();
        adminAccountRole.setAdminAccountId(one.getId());
        adminAccountRole.setRoleId(role.getId());
        adminAccountRoleService.save(adminAccountRole);
        log.info("运管平台帐号角色初始化结束");
    }


    /**
     * 前台帐号的运管平台初始化，后续弃用后台帐号
     */
    @PostConstruct
    public void startV2(){
        log.info("开始初始化运管帐号默认角色 V2");

        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("app_id", "202211244024");
        App app = null;
        try {
            app = appService.getOne(appQueryWrapper);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(null == app){
            log.warn("运管平台app不存在，初始化终止");
            return;
        }


        QueryWrapper<Permission> permissionQuery = new QueryWrapper<>();
        permissionQuery.eq("app_id", app.getId());
        List<Permission> list = permissionService.list(permissionQuery);
        if(list.isEmpty()){
            log.warn("应用 202211244024 缺少菜单，请先导入");
            return;
        }
        // 运管平台的所有权限
        List<Integer> permissions = list.stream().map(i -> i.getId()).collect(Collectors.toList());

        // 角色部分
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("code", "oamadmin");
        Role role = null;
        try {
            role = roleService.getOne(roleQueryWrapper);
        }catch (Exception e){
            log.error("初始化角色失败，初始化运管终止");
            return;
        }
        if(null == role){
            role = new Role();
            role.setIndustryId((short)10);
            role.setName("管理员");
            role.setCode("oamadmin");
            role.setGrade((short)2);
            role.setType(3);
            role.setIsInitialized(true);
            role.setLevel(1);
            role.setSortNum(1);
            role.setParentId(0);
            role.setStatus((short) 1);
            role.setIsDeleted(false);
            role.setAppId(app.getId());
            roleService.save(role);
        }

        // 给角色绑定权限
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("role_id", role.getId());
        List<RolePermission> list1 = rolePermissionService.list(rolePermissionQueryWrapper);
        if(!list1.isEmpty()){
            List<Integer> collect1 = list1.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());
            if(collect1.contains(permissions.get(0))){
                log.warn("角色 oamadmin 已经关联了运管平台的权限，不需要给角色增加权限了");
            }else{
                // 给角色绑定初始化的运管权限
                List<RolePermission> rolePermissions = new ArrayList<>();
                for (Integer permission : permissions) {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setPermissionId(permission);
                    rolePermission.setRoleId(role.getId());
                    rolePermissions.add(rolePermission);
                }
                rolePermissionService.saveBatch(rolePermissions);
            }
        }else{
            // 给角色绑定初始化的运管权限
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (Integer permission : permissions) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setPermissionId(permission);
                rolePermission.setRoleId(role.getId());
                rolePermissions.add(rolePermission);
            }
            rolePermissionService.saveBatch(rolePermissions);
        }


        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("login_name", "admin");
        accountQueryWrapper.eq("is_deleted", false);
        Account account = null;
        try {
             account = accountService.getOne(accountQueryWrapper);
        }catch (Exception e){
            log.error("查询运管帐号 admin 失败， 初始化运管平台的权限终止");
            return;
        }
        if(null == account){
            log.info("缺少运管帐号，现在创建运管 admin 帐号");
            account = new Account();
            account.setLoginName("admin");
            account.setPassword("user@123");
            account.setNickname("管理员");
            account.setName("管理员");
            account.setStatus((short)1);
            account.setIsDeleted(false);
            account.setDevelopId(developerService.getDefault().getId());
            AccountRelation accountRelation = new AccountRelation();
            accountRelation.setRoleIds(Arrays.asList(role.getId()));

            List<PermissionGroupDTO> permissionGroupDTOS = new ArrayList<>();
            PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
            permissionGroupDTO.setRoleIds(String.valueOf(role.getId()));
            permissionGroupDTO.setRoleList(Arrays.asList(role.getId()));
            permissionGroupDTOS.add(permissionGroupDTO);
            accountService.createAccountV2(account, accountRelation, permissionGroupDTOS);
        }else{
            log.info("已经存在 login_name 为 admin的帐号");
        }
        log.info("初始化运管平台帐号完成！");
    }
}
